package com.auleev.date;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

/**
 * Utility class used for date normalization.
 * 
 * @author bminciu
 */
public class DateNormalizer {

    // Private constructor prevents instantiation from other classes
    private DateNormalizer() {
    }

    /**
     * SingletonHolder is loaded on the first execution of DateNormalizer.getInstance()
     * or the first access to SingletonHolder.INSTANCE, not before.
     * 
     * http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom
     */
    private static class SingletonHolder {

        private static final DateNormalizer INSTANCE = new DateNormalizer();
    }

    public static DateNormalizer getInstance() {
        return SingletonHolder.INSTANCE;
    }

    /**
     * Returns the date specified as 'timeInMillis' normalized
     * from this form: 'yyyy-MM-dd hh:mm:ss.SSSS' to this form:
     * 'yyyy-MM-dd 00:00:00.0000'
     *
     * @param timeInMillis
     * @return
     */
    public long normalizeDate(final long timeInMillis) {
        final Calendar cal = GregorianCalendar.getInstance(Locale.FRANCE);
        cal.setTimeInMillis(timeInMillis);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);

        return cal.getTimeInMillis();
    }

    /**
     * @see <code>DateNormalizer.normalizeDate(final long timeInMillis)</code>
     * 
     * @param date
     * @return
     */
    public Date normalizeDate(final Date date) {
        Date result = new java.util.Date();
        result.setTime(normalizeDate(date.getTime()));
        return result;
    }
}
